#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>

class ThreadData
{
public:
    int Excute()
    {
        return x + y;
    }
public:
    std::string name;
    //int num;
    int x;
    int y;
};

class ThreadResult
{
public:
    std::string Print()
    {
        return std::to_string(x) + " + " + std::to_string(y) + " = " + std::to_string(result) ;
    }
public:
    int x;
    int y;
    int result;
};

void* threadRun(void* args)
{
    // std::string name = (const char*) args;
    ThreadData* td = static_cast<ThreadData*> (args);

    ThreadResult* result = new ThreadResult();
    int cnt = 5;
    while(cnt)
    {
        std::cout << td->name << " run..." << std::endl;
        result->result = td->Excute();
        result->x = td->x;
        result->y = td->y;
        break;
        sleep(1);
    }
    delete td;
    return (void*)result;
}

std::string PrintToHex(pthread_t &tid)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%lx", tid);
    return buffer;
}

int main()
{
    pthread_t tid;
    // ThreadData td; 不推荐这种做法，破坏线程的独立性和完整性
    ThreadData* td = new ThreadData(); //推荐
    td->name = "thread-1";
    td->x = 1;
    td->y = 2;

    int n = pthread_create(&tid, nullptr, threadRun, td);

    if(n != 0)
    {
        std::cerr << "create thread error" << std::endl;
        return 1;
    }

    std::string tid_str = PrintToHex(tid);
    std::cout << "tid : " << tid_str << std::endl;


    std::cout << "main thread join begin..." << std::endl;

    // void* code = nullptr;
    ThreadResult* result = nullptr;
    n = pthread_join(tid, (void**)&result); // 不join会造成类似僵尸进程的问题
    
    if(n == 0)
    {
        std::cout << "main thread wait success, new thread exit code : " << result->Print() << std::endl;
    }

    return 0;
}
